<script setup lang="ts">
import { computed, reactive, ref, toRaw } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { add_new_guide_share_api } from "@/package/novice/api/new_guide";
import { upload_up } from "@/api/upload";
import { chooseMedia, uploadWrapper, previewImage } from "@/utils/meida";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import EditVideoPoster from "./components/edit-video-poster.vue";
import FormUpload from "@/components/form/upload.vue";
import IconClose from "@/components/icon/close.vue";
import FormEditor from "@/components/form/editor.vue";
import FormButton from "@/components/form/button.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad((options) => {
  editForm.type = options?.type || "1"; // 1：图文；2：视频；3：长文本

  if (options?.filePath) {
    tempData.filePath = decodeURIComponent(options.filePath);
  }
});

const editForm = reactive({
  id: "",
  type: "",
  title: "",
  content: "",
  img_arr: [] as string[],
  video_url: "",
  video_pic: "",
});

const imgClick = (type: "del" | "upload", index: number) => {
  if (type === "del") {
    editForm.img_arr.splice(index, 1); // 视频封面没有删除，只有替换
  } else if (type === "upload") {
    chooseMedia(
      {
        count: editForm.type === "2" ? 1 : 9 - editForm.img_arr.length,
        mediaType: ["image"],
      },
      (resp) => {
        Toast.showLoading();
        uploadWrapper(
          resp.map((i) => i.tempFilePath),
          (resp) => {
            editForm.type === "2"
              ? (editForm.video_pic = resp[0])
              : editForm.img_arr.push(...resp);
            Toast.hideLoading();
          },
          (path) => {
            return upload_up(path, { type: "0" }).then((resp) => {
              return resp.map((i) => i.url);
            });
          }
        );
      }
    );
  } else {
    // 视频封面没有预览
    editForm.type === "2"
      ? Router.navigateTo(
          `/package/other/pages/video/detail?${Router.dataToQuery({
            src: tempData.filePath,
            poster: editForm.video_pic,
          })}`
        )
      : previewImage(toRaw(editForm.img_arr), index);
  }
};

const submitClick = () => {
  const fn = () => {
    return add_new_guide_share_api(toRaw(editForm)).then(() => {
      Toast.hideLoading();
      popupModal.value?.show(
        {
          content: "发布成功",
          showCancel: false,
          confirmText: "我知道了",
        },
        () => Router.navigateBack()
      );
    });
  };

  Toast.showLoading();
  if (editForm.type === "1") {
    fn().catch(() => Toast.hideLoading());
  } else if (editForm.type === "2") {
    upload_up(tempData.filePath, { type: 6 })
      .then((resp) => {
        editForm.video_url = resp[0].url;
        return fn();
      })
      .catch(() => Toast.hideLoading());
  } else {
    formEditor.value?.getContents((resp) => {
      editForm.content = resp.html;
      fn().catch(() => Toast.hideLoading());
    });
  }
};

const editorFocus = ref(false);

const formEditor = ref<InstanceType<typeof FormEditor>>();
const popupModal = ref<InstanceType<typeof PopupModal>>();
const tempData = { filePath: "" };
</script>

<template>
  <view class="edit-img" v-if="editForm.type === '1'">
    <view class="edit-img-upload" @click="imgClick('upload')">
      <FormUpload />
    </view>
    <scroll-view
      class="edit-img-wrapper"
      scroll-x
      enhanced
      :show-scrollbar="false"
    >
      <view class="edit-img-space"></view>
      <view class="edit-img-item" v-for="(i, d) of editForm.img_arr" :key="i">
        <image
          class="edit-img-source"
          :src="i"
          mode="aspectFill"
          @click="imgClick('preview', d)"
        />
        <view class="edit-img-del" @click="imgClick('del', d)">
          <IconClose size="24rpx" color="rgba(255, 255, 255, 0.8)" />
        </view>
      </view>
    </scroll-view>
  </view>
  <view class="edit-video" v-else-if="editForm.type === '2'">
    <view class="edit-video-poster">
      <view @click="imgClick('upload')">
        <EditVideoPoster :url="editForm.video_pic" />
      </view>
    </view>

    <view class="edit-video-play" @click="imgClick('preview')">
      <image
        class="edit-video-play2"
        src="@/package/novice/static/note-edit-play.png"
      />
      预览视频
    </view>
  </view>

  <view class="edit-form">
    <view class="edit-form-title">
      <input
        class="edit-form-input"
        v-model="editForm.title"
        placeholder="添加标题"
      />
    </view>
    <view class="edit-form-line"></view>
    <FormEditor
      className="edit-form-content"
      v-model="editorFocus"
      v-if="editForm.type === '3'"
      placeholder="添加正文"
      ref="formEditor"
    />
    <textarea
      class="edit-form-content"
      v-else
      v-model="editForm.content"
      auto-height
      placeholder="添加正文"
    />
    <view class="edit-form-line"></view>
  </view>

  <view class="edit-btn" v-if="!editorFocus">
    <view @click="submitClick">
      <FormButton :disabled="editForm.title.length === 0">发布</FormButton>
    </view>
  </view>

  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
page {
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;
}

.edit-img {
  position: relative;
  padding-left: 210rpx;

  .edit-img-upload {
    position: absolute;
    left: 30rpx;
    top: 20rpx;
    width: 180rpx;
    height: 180rpx;
  }

  .edit-img-wrapper {
    width: 100%;
    height: 220rpx;
    white-space: nowrap;
  }

  .edit-img-space,
  .edit-img-item {
    display: inline-block;
    vertical-align: top;
  }

  .edit-img-space {
    width: 10rpx;
  }

  .edit-img-item {
    position: relative;
    margin-top: 20rpx;
    margin-right: 10rpx;
  }

  .edit-img-source {
    display: block;
    width: 180rpx;
    height: 180rpx;
    border-radius: 20rpx;
  }

  .edit-img-del {
    position: absolute;
    top: 0;
    right: 0;
    padding: 4rpx;
    border-radius: 0 20rpx 0 10rpx;
    background: rgba(0, 0, 0, 0.5);
  }
}

.edit-video {
  padding-left: 30rpx;
  padding-top: 20rpx;

  .edit-video-poster {
    display: flex;
    margin-bottom: 20rpx;
  }

  .edit-video-play {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 160rpx;
    height: 56rpx;
    font-size: 24rpx;
    color: #333333;
    line-height: 36rpx;
    border-radius: 28rpx;
    background-color: #f2f2f2;
  }

  .edit-video-play2 {
    width: 16rpx;
    height: 22rpx;
    margin-right: 8rpx;
  }
}

.edit-form {
  margin-bottom: 20rpx;

  .edit-form-title {
    display: flex;
    align-items: center;
    height: 104rpx;
    padding: 0 30rpx;
  }

  .edit-form-input {
    flex-grow: 1;
    min-width: 0;
    font-size: 32rpx;
    color: #333333;
    font-weight: bold;
  }

  .edit-form-line {
    margin: 0 30rpx;
    border-radius: 2rpx;
    border-bottom: 2rpx solid #eeeeee;
  }

  .edit-form-content {
    display: block;
    width: 100%;
    min-height: 440rpx;
    padding: 30rpx;
    font-size: 30rpx;
    color: #333333;
    line-height: 42rpx;
    background-color: transparent;
    box-sizing: border-box;
  }

  .ql-container {
    .ql-blank::before {
      font-style: normal;
    }
  }
}

.edit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 106rpx;
  padding: 14rpx 60rpx env(safe-area-inset-bottom);
  background-color: #ffffff;
  box-shadow: 0 4rpx 20rpx 0 rgba(0, 0, 0, 0.2);
}
</style>